/**
 * @file test_reverse_generation.cpp
 * @brief 反向生成功能全面测试用例
 * 测试所有反向生成模式和各种模块类型
 */

#include "../moparse.h"
#include <iostream>
#include <fstream>
#include <cassert>
#include <functional>
#include <cstdio>
#include <sstream>

class ReverseGenerationTestRunner {
public:
    ReverseGenerationTestRunner() : tests_passed_(0), tests_failed_(0) {}
    
    void run_test(const std::string& test_name, std::function<bool()> test_func) {
        std::cout << "运行反向生成测试: " << test_name << " ... ";
        try {
            if (test_func()) {
                std::cout << "通过" << std::endl;
                tests_passed_++;
            } else {
                std::cout << "失败" << std::endl;
                tests_failed_++;
            }
        } catch (const std::exception& e) {
            std::cout << "异常: " << e.what() << std::endl;
            tests_failed_++;
        }
    }
    
    void print_summary() {
        std::cout << "\n反向生成测试总结:" << std::endl;
        std::cout << "通过: " << tests_passed_ << std::endl;
        std::cout << "失败: " << tests_failed_ << std::endl;
        std::cout << "总计: " << (tests_passed_ + tests_failed_) << std::endl;
    }
    
    int get_failed_count() const { return tests_failed_; }

private:
    int tests_passed_;
    int tests_failed_;
};

// 创建反向生成测试用的模块文件
void create_reverse_generation_files() {
    
    // 1. 简单模块 - 用于基本反向生成测试
    std::ofstream simple_module("test_simple_reverse.v");
    simple_module << R"(
module simple_module (
    input clk,
    input reset,
    input enable,
    output reg [7:0] count,
    output overflow
);

parameter MAX_COUNT = 255;
parameter MIN_COUNT = 0;

wire internal_clk;

always @(posedge clk or posedge reset) begin
    if (reset)
        count <= MIN_COUNT;
    else if (enable)
        count <= (count == MAX_COUNT) ? MIN_COUNT : count + 1;
end

assign overflow = (count == MAX_COUNT);
assign internal_clk = clk;

endmodule
)";
    simple_module.close();

    // 2. 复杂参数化模块
    std::ofstream complex_param_module("test_complex_param.v");
    complex_param_module << R"(
module complex_param_module #(
    parameter DATA_WIDTH = 32,
    parameter ADDR_WIDTH = 10,
    parameter [31:0] DEFAULT_VALUE = 32'hDEADBEEF,
    parameter ENABLE_CACHE = 1'b1,
    parameter CACHE_SIZE = 1024,
    parameter real TIMING_FACTOR = 1.5
) (
    input clk,
    input reset_n,
    input [DATA_WIDTH-1:0] write_data,
    input [ADDR_WIDTH-1:0] write_addr,
    input [ADDR_WIDTH-1:0] read_addr,
    input write_enable,
    input read_enable,
    output reg [DATA_WIDTH-1:0] read_data,
    output cache_hit,
    output cache_miss,
    inout [7:0] control_bus
);

localparam MEMORY_DEPTH = 1 << ADDR_WIDTH;
localparam CACHE_ADDR_WIDTH = $clog2(CACHE_SIZE);

reg [DATA_WIDTH-1:0] memory [0:MEMORY_DEPTH-1];
wire [CACHE_ADDR_WIDTH-1:0] cache_addr;

endmodule
)";
    complex_param_module.close();

    // 3. 多端口类型模块
    std::ofstream multiport_module("test_multiport.v");
    multiport_module << R"(
module multiport_module (
    // 时钟和复位
    input wire sys_clk,
    input wire user_clk,
    input wire async_reset_n,
    input wire sync_reset,
    
    // 标量端口
    input enable,
    input write_en,
    output ready,
    output valid,
    
    // 向量端口
    input [7:0] byte_data,
    input [15:0] word_data,
    input [31:0] dword_data,
    output [7:0] status_byte,
    output [15:0] result_word,
    output [31:0] result_dword,
    
    // 有符号端口
    input signed [15:0] signed_input,
    output signed [15:0] signed_output,
    
    // 数组端口
    input [7:0] input_array [0:3],
    output [7:0] output_array [0:3],
    
    // 双向端口
    inout [7:0] bidirectional_bus,
    inout tri_signal,
    
    // 特殊网络类型
    output wire wire_output,
    output reg reg_output,
    output logic logic_output
);

parameter NUM_CHANNELS = 4;
parameter [7:0] DEVICE_ID = 8'hA5;

endmodule
)";
    multiport_module.close();

    // 4. 包含宏的模块
    std::ofstream macro_module("test_macro_reverse.v");
    macro_module << R"(
`define FEATURE_A
`define DATA_WIDTH 16

module macro_module (
    input clk,
    input reset,
    
`ifdef FEATURE_A
    input feature_a_enable,
    output [7:0] feature_a_data,
`endif

`ifdef FEATURE_B
    input feature_b_enable,
    output [7:0] feature_b_data,
`endif

    input [`DATA_WIDTH-1:0] main_data,
    output reg [`DATA_WIDTH-1:0] output_data
);

parameter FEATURE_A_PARAM = 8'h5A;

`ifdef FEATURE_A
parameter FEATURE_A_SIZE = 64;
`endif

endmodule
)";
    macro_module.close();

    // 5. 嵌套层次模块
    std::ofstream hierarchical_module("test_hierarchical.v");
    hierarchical_module << R"(
module top_level_module (
    input clk,
    input reset,
    input [7:0] data_in,
    output [7:0] data_out,
    output valid
);

parameter TOP_PARAM = 42;

wire [7:0] intermediate_data;
wire intermediate_valid;

mid_level_module u_mid (
    .clk(clk),
    .reset(reset),
    .data_in(data_in),
    .data_out(intermediate_data),
    .valid(intermediate_valid)
);

output_stage u_output (
    .clk(clk),
    .data_in(intermediate_data),
    .valid_in(intermediate_valid),
    .data_out(data_out),
    .valid_out(valid)
);

endmodule

module mid_level_module (
    input clk,
    input reset,
    input [7:0] data_in,
    output [7:0] data_out,
    output valid
);

parameter MID_PARAM = 24;

low_level_processor u_processor (
    .clk(clk),
    .reset(reset),
    .input_data(data_in),
    .output_data(data_out),
    .data_valid(valid)
);

endmodule

module low_level_processor (
    input clk,
    input reset,
    input [7:0] input_data,
    output reg [7:0] output_data,
    output reg data_valid
);

parameter LOW_PARAM = 12;

always @(posedge clk) begin
    if (reset) begin
        output_data <= 8'h00;
        data_valid <= 1'b0;
    end else begin
        output_data <= input_data + 1;
        data_valid <= 1'b1;
    end
end

endmodule

module output_stage (
    input clk,
    input [7:0] data_in,
    input valid_in,
    output reg [7:0] data_out,
    output reg valid_out
);

always @(posedge clk) begin
    data_out <= data_in;
    valid_out <= valid_in;
end

endmodule
)";
    hierarchical_module.close();
}

// 清理反向生成测试文件
void cleanup_reverse_generation_files() {
    std::vector<std::string> files = {
        "test_simple_reverse.v", "test_complex_param.v", "test_multiport.v",
        "test_macro_reverse.v", "test_hierarchical.v",
        "reverse_test.modb", "temp_reverse.modb",
        "simple_empty.v", "simple_stub.v", "simple_full.v", "simple_instance.v",
        "complex_empty.v", "complex_stub.v", "complex_full.v", "complex_instance.v",
        "multiport_empty.v", "multiport_stub.v", "multiport_full.v", "multiport_instance.v",
        "macro_empty.v", "macro_stub.v", "macro_full.v", "macro_instance.v",
        "hierarchical_empty.v", "hierarchical_stub.v", "hierarchical_full.v", "hierarchical_instance.v"
    };
    
    for (const auto& file : files) {
        std::remove(file.c_str());
    }
}

// 辅助函数：检查生成文件的内容
bool check_generated_file_content(const std::string& filename, const std::string& expected_module_name, const std::string& mode) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        return false;
    }
    
    std::string content;
    std::string line;
    while (std::getline(file, line)) {
        content += line + "\n";
    }
    
    // 检查是否包含模块名
    if (content.find(expected_module_name) == std::string::npos) {
        return false;
    }
    
    // 根据模式检查特定内容
    if (mode == "e") { // 空壳模式
        return content.find("module " + expected_module_name) != std::string::npos &&
               content.find("endmodule") != std::string::npos;
    } else if (mode == "es") { // 空壳+stub模式
        return content.find("module " + expected_module_name) != std::string::npos &&
               content.find("assign") != std::string::npos &&
               content.find("endmodule") != std::string::npos;
    } else if (mode == "a") { // 完整模式
        return content.find("module " + expected_module_name) != std::string::npos;
    } else if (mode == "i") { // 实例模式
        return content.find(expected_module_name + " ") != std::string::npos ||
               content.find(expected_module_name + "(") != std::string::npos;
    }
    
    return false;
}

// 测试简单模块的反向生成
bool test_simple_module_reverse_generation() {
    VerilogParser parser;
    
    // 解析模块
    if (!parser.parseVerilogFile("test_simple_reverse.v")) {
        return false;
    }
    
    if (!parser.saveToModb("temp_reverse.modb")) {
        return false;
    }
    
    // 测试所有四种反向生成模式
    if (!parser.generateVerilog("temp_reverse.modb", "simple_module", "simple_empty.v", "e")) {
        return false;
    }
    
    if (!parser.generateVerilog("temp_reverse.modb", "simple_module", "simple_stub.v", "es")) {
        return false;
    }
    
    if (!parser.generateVerilog("temp_reverse.modb", "simple_module", "simple_full.v", "a")) {
        return false;
    }
    
    if (!parser.generateVerilog("temp_reverse.modb", "simple_module", "simple_instance.v", "i")) {
        return false;
    }
    
    // 验证生成的文件内容
    return check_generated_file_content("simple_empty.v", "simple_module", "e") &&
           check_generated_file_content("simple_stub.v", "simple_module", "es") &&
           check_generated_file_content("simple_full.v", "simple_module", "a") &&
           check_generated_file_content("simple_instance.v", "simple_module", "i");
}

// 测试复杂参数化模块的反向生成
bool test_complex_param_reverse_generation() {
    VerilogParser parser;
    
    if (!parser.parseVerilogFile("test_complex_param.v")) {
        return false;
    }
    
    if (!parser.saveToModb("temp_reverse.modb")) {
        return false;
    }
    
    // 测试参数化模块的反向生成
    if (!parser.generateVerilog("temp_reverse.modb", "complex_param_module", "complex_empty.v", "e")) {
        return false;
    }
    
    if (!parser.generateVerilog("temp_reverse.modb", "complex_param_module", "complex_stub.v", "es")) {
        return false;
    }
    
    if (!parser.generateVerilog("temp_reverse.modb", "complex_param_module", "complex_instance.v", "i")) {
        return false;
    }
    
    // 检查参数是否正确生成
    std::ifstream empty_file("complex_empty.v");
    std::string content;
    std::string line;
    while (std::getline(empty_file, line)) {
        content += line + "\n";
    }
    
    // 应该包含参数定义
    return content.find("DATA_WIDTH") != std::string::npos &&
           content.find("ADDR_WIDTH") != std::string::npos;
}

// 测试多端口类型模块的反向生成
bool test_multiport_reverse_generation() {
    VerilogParser parser;
    
    if (!parser.parseVerilogFile("test_multiport.v")) {
        return false;
    }
    
    if (!parser.saveToModb("temp_reverse.modb")) {
        return false;
    }
    
    // 生成不同模式
    if (!parser.generateVerilog("temp_reverse.modb", "multiport_module", "multiport_empty.v", "e")) {
        return false;
    }
    
    if (!parser.generateVerilog("temp_reverse.modb", "multiport_module", "multiport_stub.v", "es")) {
        return false;
    }
    
    // 检查端口是否正确生成
    std::ifstream file("multiport_empty.v");
    std::string content;
    std::string line;
    while (std::getline(file, line)) {
        content += line + "\n";
    }
    
    // 应该包含各种端口类型
    return content.find("input") != std::string::npos &&
           content.find("output") != std::string::npos &&
           content.find("inout") != std::string::npos &&
           content.find("[7:0]") != std::string::npos;
}

// 测试包含宏的模块反向生成
bool test_macro_module_reverse_generation() {
    VerilogParser parser;
    
    if (!parser.parseVerilogFile("test_macro_reverse.v")) {
        return false;
    }
    
    if (!parser.saveToModb("temp_reverse.modb")) {
        return false;
    }
    
    // 生成宏模块
    if (!parser.generateVerilog("temp_reverse.modb", "macro_module", "macro_empty.v", "e")) {
        return false;
    }
    
    if (!parser.generateVerilog("temp_reverse.modb", "macro_module", "macro_instance.v", "i")) {
        return false;
    }
    
    return check_generated_file_content("macro_empty.v", "macro_module", "e") &&
           check_generated_file_content("macro_instance.v", "macro_module", "i");
}

// 测试层次化模块的反向生成
bool test_hierarchical_reverse_generation() {
    VerilogParser parser;
    
    if (!parser.parseVerilogFile("test_hierarchical.v")) {
        return false;
    }
    
    if (!parser.saveToModb("temp_reverse.modb")) {
        return false;
    }
    
    // 测试顶层模块生成
    if (!parser.generateVerilog("temp_reverse.modb", "top_level_module", "hierarchical_empty.v", "e")) {
        return false;
    }
    
    // 测试中层模块生成
    if (!parser.generateVerilog("temp_reverse.modb", "mid_level_module", "mid_empty.v", "e")) {
        return false;
    }
    
    // 测试底层模块生成
    if (!parser.generateVerilog("temp_reverse.modb", "low_level_processor", "low_empty.v", "e")) {
        return false;
    }
    
    return check_generated_file_content("hierarchical_empty.v", "top_level_module", "e") &&
           check_generated_file_content("mid_empty.v", "mid_level_module", "e") &&
           check_generated_file_content("low_empty.v", "low_level_processor", "e");
}

// 测试不存在模块的错误处理
bool test_nonexistent_module_generation() {
    VerilogParser parser;
    
    if (!parser.parseVerilogFile("test_simple_reverse.v")) {
        return false;
    }
    
    if (!parser.saveToModb("temp_reverse.modb")) {
        return false;
    }
    
    // 尝试生成不存在的模块，应该失败
    return !parser.generateVerilog("temp_reverse.modb", "nonexistent_module", "error_test.v", "e");
}

// 测试无效模式的错误处理
bool test_invalid_mode_generation() {
    VerilogParser parser;
    
    if (!parser.parseVerilogFile("test_simple_reverse.v")) {
        return false;
    }
    
    if (!parser.saveToModb("temp_reverse.modb")) {
        return false;
    }
    
    // 尝试使用无效模式，应该失败
    return !parser.generateVerilog("temp_reverse.modb", "simple_module", "invalid_mode.v", "invalid");
}

// 测试空modb文件的错误处理
bool test_empty_modb_generation() {
    VerilogParser parser;
    
    // 创建空的modb文件
    if (!parser.saveToModb("empty.modb")) {
        return false;
    }
    
    // 尝试从空文件生成，应该失败
    bool result = !parser.generateVerilog("empty.modb", "any_module", "empty_test.v", "e");
    
    std::remove("empty.modb");
    return result;
}

// 测试stub模式的详细验证
bool test_stub_mode_details() {
    VerilogParser parser;
    
    if (!parser.parseVerilogFile("test_multiport.v")) {
        return false;
    }
    
    if (!parser.saveToModb("temp_reverse.modb")) {
        return false;
    }
    
    if (!parser.generateVerilog("temp_reverse.modb", "multiport_module", "stub_detail_test.v", "es")) {
        return false;
    }
    
    // 读取生成的stub文件并检查assign语句
    std::ifstream file("stub_detail_test.v");
    std::string content;
    std::string line;
    while (std::getline(file, line)) {
        content += line + "\n";
    }
    
    // stub模式应该为输出端口生成assign语句
    bool has_assign = content.find("assign") != std::string::npos;
    bool has_zero_assignment = content.find("= 0") != std::string::npos || 
                               content.find("= 8'b0") != std::string::npos ||
                               content.find("= 16'b0") != std::string::npos ||
                               content.find("= 32'b0") != std::string::npos;
    
    std::remove("stub_detail_test.v");
    return has_assign && has_zero_assignment;
}

// 测试实例模式的详细验证
bool test_instance_mode_details() {
    VerilogParser parser;
    
    if (!parser.parseVerilogFile("test_complex_param.v")) {
        return false;
    }
    
    if (!parser.saveToModb("temp_reverse.modb")) {
        return false;
    }
    
    if (!parser.generateVerilog("temp_reverse.modb", "complex_param_module", "instance_detail_test.v", "i")) {
        return false;
    }
    
    // 读取生成的实例文件
    std::ifstream file("instance_detail_test.v");
    std::string content;
    std::string line;
    while (std::getline(file, line)) {
        content += line + "\n";
    }
    
    // 实例模式应该包含参数连接和端口连接
    bool has_param_connection = content.find(".DATA_WIDTH") != std::string::npos;
    bool has_port_connection = content.find(".clk") != std::string::npos;
    bool has_instance_name = content.find("u_complex_param_module") != std::string::npos;
    
    std::remove("instance_detail_test.v");
    return has_param_connection && has_port_connection && has_instance_name;
}

// 测试批量反向生成
bool test_batch_reverse_generation() {
    VerilogParser parser;
    
    // 解析层次化文件（包含多个模块）
    if (!parser.parseVerilogFile("test_hierarchical.v")) {
        return false;
    }
    
    if (!parser.saveToModb("batch_test.modb")) {
        return false;
    }
    
    // 为每个模块生成空壳
    std::vector<std::string> modules = {
        "top_level_module", "mid_level_module", "low_level_processor", "output_stage"
    };
    
    for (const auto& module : modules) {
        std::string filename = module + "_batch.v";
        if (!parser.generateVerilog("batch_test.modb", module, filename, "e")) {
            return false;
        }
        
        if (!check_generated_file_content(filename, module, "e")) {
            return false;
        }
        
        std::remove(filename.c_str());
    }
    
    std::remove("batch_test.modb");
    return true;
}

int main() {
    std::cout << "开始反向生成功能全面测试...\n" << std::endl;
    
    // 创建反向生成测试文件
    create_reverse_generation_files();
    
    ReverseGenerationTestRunner runner;
    
    // 运行反向生成测试
    runner.run_test("简单模块反向生成", test_simple_module_reverse_generation);
    runner.run_test("复杂参数模块反向生成", test_complex_param_reverse_generation);
    runner.run_test("多端口模块反向生成", test_multiport_reverse_generation);
    runner.run_test("宏模块反向生成", test_macro_module_reverse_generation);
    runner.run_test("层次化模块反向生成", test_hierarchical_reverse_generation);
    runner.run_test("不存在模块错误处理", test_nonexistent_module_generation);
    runner.run_test("无效模式错误处理", test_invalid_mode_generation);
    runner.run_test("空modb文件错误处理", test_empty_modb_generation);
    runner.run_test("stub模式详细验证", test_stub_mode_details);
    runner.run_test("实例模式详细验证", test_instance_mode_details);
    runner.run_test("批量反向生成", test_batch_reverse_generation);
    
    // 清理测试文件
    cleanup_reverse_generation_files();
    
    // 输出测试结果
    runner.print_summary();
    
    return runner.get_failed_count() > 0 ? 1 : 0;
}